package cn.wolfcode.business.service.impl;

import cn.wolfcode.business.domain.BusAppointment;
import cn.wolfcode.business.domain.BusStatement;
import cn.wolfcode.business.mapper.BusAppointmentMapper;
import cn.wolfcode.business.service.IBusAppointmentService;
import cn.wolfcode.business.service.IBusStatementService;
import cn.wolfcode.business.util.RegexUtils;
import cn.wolfcode.business.util.VehiclePlateNoUtil;
import cn.wolfcode.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 养修信息预约Service业务层处理
 * 
 * @author wolfcode
 * @date 2025-04-19
 */
@Service
public class BusAppointmentServiceImpl implements IBusAppointmentService 
{
    @Autowired
    private BusAppointmentMapper busAppointmentMapper;
    @Autowired
    private IBusStatementService statementService;

    /**
     * 查询养修信息预约
     * 
     * @param id 养修信息预约主键
     * @return 养修信息预约
     */
    @Override
    public BusAppointment selectBusAppointmentById(Long id)
    {
        return busAppointmentMapper.selectBusAppointmentById(id);
    }

    /**
     * 查询养修信息预约列表
     * 
     * @param busAppointment 养修信息预约
     * @return 养修信息预约
     */
    @Override
    public List<BusAppointment> selectBusAppointmentList(BusAppointment busAppointment)
    {
        return busAppointmentMapper.selectBusAppointmentList(busAppointment);
    }

    /**
     * 新增养修信息预约
     * 
     * @param busAppointment 养修信息预约
     * @return 结果
     */
    @Override
    public int insertBusAppointment(BusAppointment busAppointment)
    {
        // 前端所有的逻辑后端都要再次验证一遍。
        // 传入合理化验证（参数不能为空这些）
        if(busAppointment == null){
            throw new RuntimeException("非法参数");
        }
        if(busAppointment.getCustomerPhone() == null || busAppointment.getAppointmentTime() == null
            || busAppointment.getLicensePlate() == null || busAppointment.getCarSeries() == null
            || busAppointment.getWxUserId() == null || busAppointment.getServiceType() == null){
            throw new RuntimeException("非法参数");
        }
        if (!busAppointment.getWxUserId().toString().matches("\\d+")) {
            busAppointment.setWxUserId(null);
        }
        // 手机号码合法性验证
        if(!RegexUtils.isPhoneLegal(busAppointment.getCustomerPhone())){
            throw new RuntimeException("手机号码格式有误");
        }
        // 车牌号码合法性验证
        VehiclePlateNoUtil.VehiclePlateNoEnum vehiclePlateNo =
                VehiclePlateNoUtil.getVehiclePlateNo(busAppointment.getLicensePlate());
        if(vehiclePlateNo == null){
            throw new RuntimeException("车牌号码格式有误");
        }
        // 预约时间不能早于当前系统时间。
        if(busAppointment.getAppointmentTime().before(DateUtils.getNowDate())){
            throw new RuntimeException("预约时间不能早于当前系统时间");
        }
        // 前台传递的参数中若存在重要性的默认值。那么则不能直接使用前台传递的这个对象。
        // 若一定要使用，则必须将默认值从新覆盖掉。
        // 为了安全性防止恶意攻击，我们都会重新覆盖默认值
        busAppointment.setStatus(BusAppointment.STATUS_BOOKING);
        busAppointment.setCreateTime(DateUtils.getNowDate());
        return busAppointmentMapper.insertBusAppointment(busAppointment);
    }

    /**
     * 修改养修信息预约
     * 
     * @param busAppointment 养修信息预约
     * @return 结果
     */
    @Override
    public int updateBusAppointment(BusAppointment busAppointment)
    {
        // 前端所有的逻辑后端都要再次验证一遍。
        // 传入合理化验证（参数不能为空这些）
        if(busAppointment == null){
            throw new RuntimeException("非法参数");
        }
        if(busAppointment.getCustomerPhone() == null || busAppointment.getAppointmentTime() == null
                || busAppointment.getLicensePlate() == null || busAppointment.getCarSeries() == null
                || busAppointment.getWxUserId() == null || busAppointment.getServiceType() == null){
            throw new RuntimeException("非法参数");
        }
        if (!busAppointment.getWxUserId().toString().matches("\\d+")) {
            busAppointment.setWxUserId(null);
        }
        // 必须是预约中的用户才可以进行编辑
        if(!BusAppointment.STATUS_BOOKING.equals(busAppointment.getStatus())){
            throw new RuntimeException("必须是预约中的用户才可以进行编辑操作");
        }
        // 手机号码合法性验证
        if(!RegexUtils.isPhoneLegal(busAppointment.getCustomerPhone())){
            throw new RuntimeException("手机号码格式有误");
        }
        // 车牌号码合法性验证
        VehiclePlateNoUtil.VehiclePlateNoEnum vehiclePlateNo =
                VehiclePlateNoUtil.getVehiclePlateNo(busAppointment.getLicensePlate());
        if(vehiclePlateNo == null){
            throw new RuntimeException("车牌号码格式有误");
        }
        // 预约时间不能早于当前系统时间。
        if(busAppointment.getAppointmentTime().before(DateUtils.getNowDate())){
            throw new RuntimeException("预约时间不能早于当前系统时间");
        }
        // 前台传递的参数中若存在重要性的默认值。那么则不能直接使用前台传递的这个对象。
        // 若一定要使用，则必须将默认值从新覆盖掉。
        // 为了安全性防止恶意攻击，我们都会重新覆盖默认值
        busAppointment.setStatus(BusAppointment.STATUS_BOOKING);
        return busAppointmentMapper.updateBusAppointment(busAppointment);
    }

    /**
     * 批量删除养修信息预约
     * 
     * @param ids 需要删除的养修信息预约主键
     * @return 结果
     */
    @Override
    public int deleteBusAppointmentByIds(Long[] ids)
    {
        if(!(ids != null && ids.length == 1)){
            throw new RuntimeException("非法参数");
        }
        Long id = ids[0];
        BusAppointment busAppointment = this.selectBusAppointmentById(id);
        if(busAppointment == null){
            throw new RuntimeException("非法参数");
        }
        // 必须是预约中的用户才可以进行删除操作
        if(!BusAppointment.STATUS_BOOKING.equals(busAppointment.getStatus())){
            throw new RuntimeException("必须是预约中的用户才可以进行删除操作");
        }
        return busAppointmentMapper.deleteBusAppointmentByIds(ids);
    }

    /**
     * 删除养修信息预约信息
     * 
     * @param id 养修信息预约主键
     * @return 结果
     */
    @Override
    public int deleteBusAppointmentById(Long id)
    {
        return busAppointmentMapper.deleteBusAppointmentById(id);
    }

    /**
     * 到店功能
     * @param id
     * @return
     */
    @Override
    public int arrived(Long id) {
        //  1. 传入参数合法性验证。
        if(id == null){
            throw new RuntimeException("非法参数");
        }
        BusAppointment busAppointment = this.selectBusAppointmentById(id);
        if(busAppointment == null){
            throw new RuntimeException("非法参数");
        }
        // 	2. 验证当前预约单状态必须为预约中才可以进行到店操作。
        if(!BusAppointment.STATUS_BOOKING.equals(busAppointment.getStatus())){
            throw new RuntimeException("必须是预约中的用户才可以进行到店操作");
        }

        // 	3. 需要做的事情：
        //      - 将到店时间更新到养修预约表中。
        //      - 同时将状态修改为已到店
        // 这里不要调用 update 更新所有那个方法。因为那个方法只用作前台传递参数的全部更新。
        return busAppointmentMapper.updateStatusById(DateUtils.getNowDate(),BusAppointment.STATUS_ARRIVED,id);
    }

    /**
     * 取消功能
     * @param id
     * @return
     */
    @Override
    public int cancel(Long id) {
        //  - 参数合理化验证。
        if (id == null) {
            throw new RuntimeException("非法参数");
        }
        BusAppointment busAppointment = this.selectBusAppointmentById(id);
        if (busAppointment == null) {
            throw new RuntimeException("非法参数");
        }
        // - 必须是预约中的用户才可以直接取消操作。
        if(!BusAppointment.STATUS_BOOKING.equals(busAppointment.getStatus())){
            throw new RuntimeException("必须是预约中的用户才可以进行取消操作");
        }
        //    - 将状态改为用户取消  status = 2
        return busAppointmentMapper.changeStatusById(BusAppointment.STATUS_USER_CANCELLED,id);
    }

    @Override
    public void updateStatusById(Long id, Integer status) {
        busAppointmentMapper.changeStatusById(status,id);
    }

    /**
     * 查找或生成结算单
     */
    @Override
    @Transactional
    public Long createOrSelectStatement(Long id) {
        // 参数合理化校验
        if (id == null) {
            throw new RuntimeException("非法参数");
        }
        BusAppointment busAppointment = this.selectBusAppointmentById(id);
        if(busAppointment == null){
            throw new RuntimeException("非法参数");
        }
        // 判断预约单状态 0-预约中 2-用户取消 3-超时取消都不可以点击结算单
        if(BusAppointment.STATUS_BOOKING.equals(busAppointment.getStatus()) ||
            BusAppointment.STATUS_USER_CANCELLED.equals(busAppointment.getStatus()) ||
            BusAppointment.STATUS_TIMEOUT_CANCELLED.equals(busAppointment.getStatus())){
            throw new RuntimeException("预约单处于预约中、用户取消、超时取消则不允许生成结算单");
        }
        // 根据参数（预约单 id） 查询结算单
        BusStatement statement = statementService.queryStatementByAppointmentId(id);
        // 没有查询到则新建结算单。
        if(statement == null){
            statement = new BusStatement();
            if(busAppointment.getWxUserId() == null){
                statement.setCustomerName("客服录入");
            } else {
                // 通过 id 获取用户信息，将用户名赋予。
            }
            statement.setCustomerPhone(busAppointment.getCustomerPhone());
            statement.setActualArrivalTime(busAppointment.getActualArrivalTime());
            statement.setLicensePlate(busAppointment.getLicensePlate());
            statement.setCarSeries(busAppointment.getCarSeries());
            statement.setServiceType(busAppointment.getServiceType());
            statement.setInfo(busAppointment.getInfo());
            // 将预约单 ID 也需要添加到结算单对象中
            statement.setAppointmentId(id);
            // 安全性设置
            statement.setStatus(BusStatement.STATUS_CONSUME);
            // 插入结算单
            statementService.insertBusStatement(statement);
            // 更新预约单状态
            busAppointmentMapper.changeStatusById(BusAppointment.STATUS_SETTLED,id);
        }
        // 若查询到则需要判断当前结算单 is_delete 的状态。
        if(BusStatement.IS_DELETE.equals(statement.getIsDelete())){
            // 若是被删除状态，那我们需要将其恢复。 修改 is_delete = 0
            statementService.changeIsDeleteStatus(statement.getId(),BusStatement.IS_NOT_DELETE);
            // 更新预约单状态
            busAppointmentMapper.changeStatusById(BusAppointment.STATUS_SETTLED,id);
        }
        // 返回结算单 id

        return statement.getId();
    }
}
